
#include "std_msgs/msg/u_int32.hpp"
#include "std_msgs/msg/u_int32_multi_array.hpp"
#include "voicectl_pkg/voicectrl.h"
#include <boost/thread.hpp>
#include <sys/wait.h>
#include "ament_index_cpp/get_package_share_directory.hpp"
#include "voicectl_pkg/node.h"  

rclcpp::Node::SharedPtr node;
char g_VoiceOrder[10] = {0};
int g_VoiceVolume = 0;
static int last_volumn = 0;

void wait4children(int signo) {  
	int status;  
	while(waitpid(-1, &status, WNOHANG) > 0);  
}  

void Callback(const std_msgs::msg::UInt32MultiArray::SharedPtr msg)
{
    char voiceorder[10] = {0};
    int voicevolume = 0;
    char order[4];

    sprintf(order, "%d", msg->data.at(0));
    sprintf(voiceorder, "%s.wav", order);
    voicevolume = msg->data.at(1);
    
    RCLCPP_INFO(node->get_logger(),"voice = %s volume = %d\n",voiceorder, voicevolume);
    if(last_volumn != voicevolume)
    {
        Set_Volume(voicevolume);
        last_volumn = voicevolume;
    }
    
    Play_Voice(voiceorder);
}

int main(int argc, char **argv)
{
    const std::string packname = "voicectl_pkg";
    char dir[1024] = {0};
    
    signal(SIGCHLD, wait4children);

    rclcpp::init(argc, argv);
    node =  std::make_shared<rclcpp::Node>("voicectl_pkg");
    
    std::string path = ament_index_cpp::get_package_share_directory(packname);
    sprintf(dir, "%s%s", path.c_str(), "/music/");
    RCLCPP_INFO(node->get_logger(),"dir = %s\n", dir);
    int ret = Init_Voice_File_Route(dir);
    if(ret < 0)
    {
        return -1;
    }
    rclcpp::Subscription<std_msgs::msg::UInt32MultiArray>::SharedPtr sub = node->create_subscription<std_msgs::msg::UInt32MultiArray>("Voicectl", 1, std::bind(&Callback,std::placeholders::_1));
    rclcpp::spin(node);
    // 关闭ROS2 C++接口
    rclcpp::shutdown();   
    
    return 0;
}



